package com.aios.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class FileUtil {
	private static final int KB = 1024;
	private static final int MAX_MB = 1;
	public static final String PATH_SEPERATOR = "/";
	
	public static boolean isValidSize(File file) {
		
		boolean isValid = true;
		
		if (file != null) {
			
	        long size = file.length();
	        double mb = (double) size / (KB * KB);
	        
	        if (mb > MAX_MB) {
	        	isValid = false;
	        }
	        
	    } else {
			isValid = false;
		}
		
		return isValid;
	}
	
	public static String convertStreamToString(InputStream is) throws IOException {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
 
        String line = null;
        try {
        	
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            
        } finally {
        	
            try {
                is.close();
            } catch (IOException e) {
                //nothing to do
            }
        }
        return sb.toString();
    }
	
	public static File createFolderIfNotExist(File dst, String child) throws IOException {

		File f = createFolderValidate(dst, child);
		
		if(!f.exists()) {
			f.mkdir();
		} 
		
		return f;
		
	}
	
	public static File createFolderIfNotExist(File dst, String child, String grandChild) throws IOException {
		
		File firstChild = createFolderIfNotExist(dst, child);
		return createFolderIfNotExist(firstChild, grandChild);
		
	}

	public static File createFolderIfNotExist(File dst, String... childrenHeirarchy) throws IOException {
		File f = dst;
		
		for (String s : childrenHeirarchy) {
			f = createFolderIfNotExist(f, s);
		}
		
		return f;
	}
	
	private static File createFolderValidate(File dst, String child) throws IOException {
		
		if(dst == null || child == null) {
			throw new IllegalArgumentException("Parameters cannot be null");
		}
		
		if(!dst.exists() || !dst.isDirectory()) {
			throw new IOException("Given destination does not exist or is not a folter");
		} else {
			return  new File(dst.getAbsolutePath().concat(PATH_SEPERATOR).concat(child));
		}
	}

}
